package com.njbw.log;

import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * 日志切面
 */
@Aspect
@Log4j2
@ConditionalOnProperty(name = {"log.aspect.enable"}, havingValue = "true", matchIfMissing = true) // 开关
@Component
public class LogAspect {

    @Pointcut("execution(* com.njbw.*.controller.*Controller.*(..)) || execution(* com.njbw.*.service.*Service.*(..))")
    private void pointCut() {}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        // -------------------打印入参
        // 获取方法参数
        Object[] reqArgs = pjp.getArgs();
        String req = new Gson().toJson(reqArgs);
        // 获取方法相关信息
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        String methodName = methodSignature.getDeclaringTypeName() + "." + methodSignature.getName();
        if (log.isInfoEnabled()) {
            log.info("{}, req: {}", methodName, req);
        }
        Long startTime = System.currentTimeMillis();
        // 执行业务方法
        Object responseObj = pjp.proceed();// 异常一定要抛出去
        String resp = new Gson().toJson(responseObj);
        Long endTime = System.currentTimeMillis();
        if (log.isInfoEnabled()) {
            log.info("{}, response: {}, costTime: {} ms", methodName, resp, endTime - startTime);
        }
        return responseObj;
    }
}
